//
//  ReaderQRCodeViewController.m
//  QRMaster
//
//  Created by myApple on 15/7/1.
//  Copyright (c) 2015年 myApple. All rights reserved.
//

#import "ReaderQRCodeViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "ShowQRCodeController.h"
#import "ZBarSDK.h"

#define SCANVIEW_EdgeTop 40.0
#define SCANVIEW_EdgeLeft 50.0

#define TINTCOLOR_ALPHA 0.4  //浅色透明度
#define DARKCOLOR_ALPHA 0.5  //深色透明度

static SystemSoundID shake_sound_male_id = 0;

static SystemSoundID shake_sound_refresh = 1;

@interface ReaderQRCodeViewController ()<AVCaptureMetadataOutputObjectsDelegate,ZBarReaderDelegate,UIAlertViewDelegate,ZBarReaderViewDelegate>
{
    UIView *_QrCodeline;
    NSTimer *_timer;
    
    //设置扫描画面
    UIView *_scanView;
    ZBarReaderView *_readerView;
    UIButton *openButton;
    
    //多语言
    UILabel *labIntroudction;
}

@end

@implementation ReaderQRCodeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self prepareNextView];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

}
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.navigationItem.title = NSLocalizedString(@"QRCodeScan", nil);
    labIntroudction.text=NSLocalizedString(@"scanShow", nil);
    [openButton setTitle:NSLocalizedString(@"openFlash", nil) forState:UIControlStateNormal];

    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    if (_readerView.torchMode ==1) {
        _readerView.torchMode =0;
        [openButton setTitle:NSLocalizedString(@"openFlash", nil)forState:0];
    }
    [self stopTimer];
    
    [_readerView stop];
    
}

-(void)stopReading:(NSString * )string
{
    //扫描音效（类似于微信音效）
    NSString * path = [[NSBundle mainBundle]pathForResource:@"5383" ofType:@"wav"];
    if (path) {
        AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:path], &shake_sound_male_id);
        AudioServicesPlayAlertSound(shake_sound_male_id);
    }
    
    ShowQRCodeController * scc = [[ShowQRCodeController alloc]init];
    scc.readerQRCodeString = string;
    [self.navigationController pushViewController:scc animated:YES];
}

-(void)prepareNextView
{
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    float ScreenHeight = [UIScreen mainScreen].bounds.size.height;
    //初始化扫描界面
    [self setScanView];
    
    _readerView= [[ZBarReaderView alloc]init];
    _readerView.frame =CGRectMake(0,0,ScreenWidth, ScreenHeight);
    _readerView.tracksSymbols= NO;
    _readerView.readerDelegate =self;
    
//    ZBarImageScanner * scanner = _readerView.scanner;
//    [scanner setSymbology:ZBAR_I25 config:ZBAR_CFG_ENABLE to:0];
    
    [_readerView addSubview:_scanView];
    //关闭闪光灯
    _readerView.torchMode =0;
    
    [self.view addSubview:_readerView];
    
    [_readerView start];
    
    [self createTimer];
}

//二维码的扫描区域
- (void)setScanView
{
    float VIEW_WIDTH = [UIScreen mainScreen].bounds.size.width;
    float VIEW_HEIGHT = [UIScreen mainScreen].bounds.size.height;
    _scanView=[[UIView alloc]initWithFrame:CGRectMake(0,0,VIEW_WIDTH,VIEW_HEIGHT-64)];
    _scanView.backgroundColor=[UIColor clearColor];
    
    //最上部view
    UIView* upView = [[UIView alloc]initWithFrame:CGRectMake(0,0,VIEW_WIDTH,SCANVIEW_EdgeTop)];
    upView.alpha =TINTCOLOR_ALPHA;
    upView.backgroundColor = [UIColor blackColor];
    [_scanView addSubview:upView];
    
    //左侧的view
    UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(0,SCANVIEW_EdgeTop,SCANVIEW_EdgeLeft,VIEW_WIDTH-2*SCANVIEW_EdgeLeft)];
    leftView.alpha =TINTCOLOR_ALPHA;
    leftView.backgroundColor = [UIColor blackColor];
    [_scanView addSubview:leftView];
    
    /******************中间扫描区域****************************/
    UIImageView *scanCropView=[[UIImageView alloc]initWithFrame:CGRectMake(SCANVIEW_EdgeLeft,SCANVIEW_EdgeTop,VIEW_WIDTH-2*SCANVIEW_EdgeLeft,VIEW_WIDTH-2*SCANVIEW_EdgeLeft)];
    //scanCropView.image=[UIImage imageNamed:@""];
    
    scanCropView.layer.borderColor=[UIColor whiteColor].CGColor;
    scanCropView.layer.borderWidth=1.0;
    
    scanCropView.backgroundColor=[UIColor clearColor];
    [_scanView addSubview:scanCropView];
    
    
    //右侧的view
    UIView *rightView = [[UIView alloc]initWithFrame:CGRectMake(VIEW_WIDTH-SCANVIEW_EdgeLeft,SCANVIEW_EdgeTop,SCANVIEW_EdgeLeft,VIEW_WIDTH-2*SCANVIEW_EdgeLeft)];
    rightView.alpha =TINTCOLOR_ALPHA;
    rightView.backgroundColor = [UIColor blackColor];
    [_scanView addSubview:rightView];
    
    
    //底部view
    UIView *downView = [[UIView alloc]initWithFrame:CGRectMake(0,VIEW_WIDTH-2*SCANVIEW_EdgeLeft+SCANVIEW_EdgeTop,VIEW_WIDTH,VIEW_HEIGHT-(VIEW_WIDTH-2*SCANVIEW_EdgeLeft+SCANVIEW_EdgeTop)-64)];
    //downView.alpha = TINTCOLOR_ALPHA;
    downView.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:TINTCOLOR_ALPHA];
    [_scanView addSubview:downView];
    
    //用于说明的label
    labIntroudction= [[UILabel alloc]init];
    labIntroudction.backgroundColor = [UIColor clearColor];
    labIntroudction.frame=CGRectMake(0,5,VIEW_WIDTH,20);
    labIntroudction.numberOfLines=1;
    labIntroudction.font=[UIFont systemFontOfSize:15.0];
    labIntroudction.textAlignment=NSTextAlignmentCenter;
    labIntroudction.textColor=[UIColor whiteColor];
    labIntroudction.text=NSLocalizedString(@"scanShow", nil);
    [downView addSubview:labIntroudction];
    
    UIView *darkView = [[UIView alloc]initWithFrame:CGRectMake(0, downView.frame.size.height-100.0,VIEW_WIDTH,100.0)];
    darkView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:DARKCOLOR_ALPHA];
    [downView addSubview:darkView];
    
    //用于开关灯操作的button
    openButton=[[UIButton alloc]initWithFrame:CGRectMake(20,20,VIEW_WIDTH - 2 * 20, 40.0)];
    [openButton setTitle:NSLocalizedString(@"openFlash", nil) forState:UIControlStateNormal];
    [openButton setTitleColor:[UIColor whiteColor]forState:UIControlStateNormal];
    openButton.titleLabel.textAlignment=NSTextAlignmentCenter;
    openButton.backgroundColor=[UIColor greenColor];
    openButton.titleLabel.font=[UIFont systemFontOfSize:22.0];
    [openButton addTarget:self action:@selector(openLight)forControlEvents:UIControlEventTouchUpInside];
    [darkView addSubview:openButton];
    
    //画中间的基准线
    _QrCodeline = [[UIView alloc]initWithFrame:CGRectMake(SCANVIEW_EdgeLeft,SCANVIEW_EdgeTop,VIEW_WIDTH-2*SCANVIEW_EdgeLeft,2)];
    _QrCodeline.backgroundColor = [UIColor whiteColor];
    [_scanView addSubview:_QrCodeline];
}
- (void)openLight
{
    if (_readerView.torchMode ==0) {
        _readerView.torchMode =1;
        [openButton setTitle:NSLocalizedString(@"closeFlash", nil) forState:0];
        
    }else
    {
        _readerView.torchMode =0;
        [openButton setTitle:NSLocalizedString(@"openFlash", nil) forState:0];
    }
}

//二维码的横线移动
- (void)moveUpAndDownLine
{
    float VIEW_WIDTH = [UIScreen mainScreen].bounds.size.width;
    CGFloat Y=_QrCodeline.frame.origin.y;
    if (VIEW_WIDTH-2*SCANVIEW_EdgeLeft+SCANVIEW_EdgeTop==Y){
        
        [UIView beginAnimations:@"asa" context:nil];
        [UIView setAnimationDuration:1];
        _QrCodeline.frame=CGRectMake(SCANVIEW_EdgeLeft, SCANVIEW_EdgeTop, VIEW_WIDTH-2*SCANVIEW_EdgeLeft,1);
        [UIView commitAnimations];
    }else if(SCANVIEW_EdgeTop==Y){
        [UIView beginAnimations:@"asa" context:nil];
        [UIView setAnimationDuration:1];
        _QrCodeline.frame=CGRectMake(SCANVIEW_EdgeLeft, VIEW_WIDTH-2*SCANVIEW_EdgeLeft+SCANVIEW_EdgeTop, VIEW_WIDTH-2*SCANVIEW_EdgeLeft,1);
        [UIView commitAnimations];
    }
    
}

-(void)readerView:(ZBarReaderView *)readerView didReadSymbols:(ZBarSymbolSet *)symbols fromImage:(UIImage *)image
{

    
 
    ZBarSymbol * symbol = nil;
    for (symbol in symbols) {
        break;
    }
    NSString * symbolStr = symbol.data;
    if ([symbolStr canBeConvertedToEncoding:NSShiftJISStringEncoding])
        
    {
        
        symbolStr = [NSString stringWithCString:[symbol.data cStringUsingEncoding: NSShiftJISStringEncoding] encoding:NSUTF8StringEncoding];
        
    }
    [self stopReading:symbolStr];
    

}


- (void)createTimer
{
    //创建一个时间计数
    _timer=[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(moveUpAndDownLine) userInfo:nil repeats:YES];
}

- (void)stopTimer
{
    if ([_timer isValid] ==YES) {
        [_timer invalidate];
        _timer =nil;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
